import { createRouter, createWebHashHistory } from 'vue-router'
import { getUserInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: () => import(/* webpackChunkName: "dashboard" */ /* webpackPrefetch: true */ '@/views/Dashboard.vue'),
    meta: { 
      requiresAuth: true,
      keepAlive: true,
      title: '工作台'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "register" */ '@/views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/set-password',
    name: 'SetPassword',
    component: () => import(/* webpackChunkName: "set-password" */ '@/views/SetPassword.vue'),
    meta: { 
      requiresAuth: true,
      isPasswordPage: true
    }
  },
  {
    path: '/twitter',
    name: 'Twitter',
    component: () => import(/* webpackChunkName: "twitter" */ '@/views/Twitter.vue'),
    meta: { requiresAuth: true }
  },
  // 临时注释掉短信中心路由
  // {
  //   path: '/sms',
  //   name: 'SMS',
  //   component: () => import(/* webpackChunkName: "sms" */ '@/views/SMS.vue'),
  //   meta: { requiresAuth: true }
  // },
  {
    path: '/linkedin',
    name: 'LinkedIn',
    component: () => import(/* webpackChunkName: "linkedin" */ '@/views/LinkedIn.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/facebook',
    name: 'Facebook',
    component: () => import(/* webpackChunkName: "facebook" */ '@/views/Facebook.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/global-enterprise',
    name: 'GlobalEnterprise',
    component: () => import(/* webpackChunkName: "global-enterprise" */ '@/views/GlobalEnterprise.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/canton-fair-purchasers',
    name: 'CantonFairPurchasers',
    component: () => import(/* webpackChunkName: "canton-fair-purchasers" */ '@/views/CantonFairPurchasers.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/canton-fair-exhibitors',
    name: 'CantonFairExhibitors',
    component: () => import(/* webpackChunkName: "canton-fair-exhibitors" */ '@/views/CantonFairExhibitors.vue'),
    meta: { requiresAuth: true }
  },
  // 海关数据相关路由 - 已注释掉
  // {
  //   path: '/customs-trade-info',
  //   name: 'CustomsTradeInfo',
  //   component: () => import(/* webpackChunkName: "customs-trade-info" */ '@/views/CustomsTradeInfo.vue'),
  //   meta: { requiresAuth: true }
  // },
  // {
  //   path: '/customs',
  //   redirect: '/customs-trade-info'
  // },
  {
    path: '/guide',
    name: 'Guide',
    component: () => import(/* webpackChunkName: "guide" */ '@/views/Guide.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/email',
    name: 'Email',
    component: () => import(/* webpackChunkName: "email" */ '@/views/Email.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/personal-center',
    name: 'PersonalCenter',
    component: () => import(/* webpackChunkName: "personal-center" */ '@/views/PersonalCenter.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/promotion',
    name: 'Promotion',
    component: () => import(/* webpackChunkName: "promotion" */ '@/views/Promotion.vue'),
    meta: {
      requiresAuth: true,
      title: '推广返佣'
    }
  },
  {
    path: '/recharge',
    name: 'Recharge',
    component: () => import(/* webpackChunkName: "recharge" */ '@/views/Recharge.vue'),
    meta: {
      requiresAuth: true,
      title: '账户充值',
      icon: 'el-icon-wallet'
    }
  },
  {
    path: '/intelligent-mail-search',
    name: 'IntelligentMailSearch',
    component: () => import(/* webpackChunkName: "intelligent-mail-search" */ '@/views/IntelligentMailSearch.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/email-reverse-check',
    name: 'EmailReverseCheck',
    component: () => import(/* webpackChunkName: "email-reverse-check" */ '@/views/EmailReverseCheck.vue'),
    meta: {
      title: '邮件反查',
      icon: 'el-icon-message',
      requiresAuth: true
    }
  },
  {
    path: '/domain-reverse-check',
    name: 'DomainReverseCheck',
    component: () => import(/* webpackChunkName: "domain-reverse-check" */ '@/views/DomainReverseCheck.vue'),
    meta: {
      title: '域名反查',
      icon: 'el-icon-link',
      requiresAuth: true
    }
  },
  {
    path: '/social-media-reverse-check',
    name: 'SocialMediaReverseCheck',
    component: () => import(/* webpackChunkName: "social-media-reverse-check" */ '@/views/SocialMediaReverseCheck.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/terms-of-service',
    name: 'TermsOfService',
    component: () => import(/* webpackChunkName: "terms-of-service" */ '@/views/TermsOfService.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/privacy-policy',
    name: 'PrivacyPolicy',
    component: () => import(/* webpackChunkName: "privacy-policy" */ '@/views/PrivacyPolicy.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/export-records',
    name: 'ExportRecords',
    component: () => import(/* webpackChunkName: "export-records" */ '@/views/ExportRecords.vue'),
    meta: { 
      requiresAuth: true,
      title: '我的导出',
      icon: 'el-icon-download'
    }
  },
  {
    path: '/main/recharge',
    name: 'RechargeRedirect',
    redirect: to => {
      const query = { ...to.query };
      return { path: '/recharge', query };
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import(/* webpackChunkName: "notfound" */ '@/views/NotFound.vue'),
    meta: { requiresAuth: false }
  }
]

// 创建路由实例 - 使用哈希路由模式
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  }
})

// 不需要登录验证的路由路径列表
const publicPages = ['/login', '/register', '/terms-of-service', '/privacy-policy'];

// 修改路由守卫，添加所有页面的登录检查
router.beforeEach(async (to, from, next) => {
  // 检查当前路由是否需要登录验证
  const requiresAuth = to.meta.requiresAuth !== false;
  const isPublicPage = publicPages.includes(to.path);
  
  // 不需要登录的页面直接通过
  if (!requiresAuth || isPublicPage) {
    // 已登录用户访问登录页，重定向到首页
    if (to.path === '/login' && localStorage.getItem('token')) {
      next('/');
      return;
    }
    next();
    return;
  }
  
  // 需要登录验证的页面，检查登录状态
  const token = localStorage.getItem('token');
  if (!token) {
    // 记录当前尝试访问的路径，登录后可以重定向回来
    localStorage.setItem('redirectPath', to.fullPath);
    next('/login');
    return;
  }
  
  // 检查token格式是否有效
  if (token.split('.').length !== 3) {
    localStorage.removeItem('token');
    localStorage.setItem('redirectPath', to.fullPath);
    ElMessage.warning('登录已过期，请重新登录');
    next('/login');
    return;
  }
  
  // 如果用户已登录，检查是否需要设置密码
  const isFirstLogin = localStorage.getItem('isFirstLogin') === 'true';
  if (isFirstLogin && !to.meta.isPasswordPage) {
    next('/set-password');
    return;
  }
  
  // 其他情况正常导航
  next();
})

// 添加路由解析完成后的处理
router.afterEach((to, from) => {
  // 设置文档标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 数海领航`;
  } else {
    document.title = '数海领航';
  }
})

// 简化错误处理
router.onError((error) => {

})

export default router 